<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'m8:machine:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="70%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #remarks="{ model, field }">
        <WangEditor
          v-model:value="model[field]"
          :bizKey="record.id"
          :bizType="'testDataChild_' + field"
          :height="300"
        />
      </template>
      <template #machineChildList>
        <BasicTable @register="registerMachineChildTable" @row-click="handleMachineChildRowClick">
          <template #testDataChildUpload="{ record: childRecord }">
            <BasicUpload
              v-model:value="childRecord.dataMap"
              :bizKey="childRecord.id"
              :bizType="'testDataChild_file'"
              :uploadType="'all'"
              :loadTime="record.__t"
            />
          </template>
        </BasicTable>
        <!-- <a-button class="mt-2" @click="handleTestDataChildAdd" v-auth="'m8:machine:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsTestTestDataForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { TestData, testDataSave, testDataForm } from '/@/api/test/testData';
  import { officeTreeData } from '/@/api/sys/office';
  import { operTreeData } from '/@/api/bas/oper';
  import { areaTreeData } from '/@/api/sys/area';
  import { BasicUpload } from '/@/components/Upload';
  import { WangEditor } from '/@/components/WangEditor';

  import { machineSave, machineForm } from '/@/api/m8/machine/machine';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('test.testData');
  const { showMessage } = useMessage();
  const record = ref<TestData>({} as TestData);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增数据') : t('编辑数据'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('机床编号'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      rules: [{ required: true }, { pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('机床名称'),
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('负责工序'),
      field: 'operCodes',
      fieldLabel: 'operNames',
      component: 'TreeSelect',
      // required: true,
      componentProps: {
        api: operTreeData,
        treeCheckable: true,
        params: {
          isShowCode: false,
          bsx: 1,
        },
        immediate: true,
        canSelectParent: true,
        allowClear: true,
        onChange: operChange,
      },
      // itemProps: { validateTrigger: 'blur' },
    },
    {
      label: t('负责人'),
      field: 'managerCodes',
      fieldLabel: 'managerNames',
      component: 'TreeSelect',
      // required: true,
      componentProps: {
        api: officeTreeData,
        // params: { isLoadUser: true, userIdPrefix: '' },
        treeCheckable: true,
        params: {
          isAll: true,
          isLoadUser: true,
        },
        immediate: true,
        canSelectParent: true,
        allowClear: true,
      },
    },

    {
      label: t('工序等级'),
      field: 'machineChildList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'machineChildList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue, updateSchema }] =
    useForm({
      labelWidth: 120,
      schemas: inputFormSchemas,
      baseColProps: { lg: 24, md: 24 },
    });

  const [registerMachineChildTable, machineChildList] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleMachineChildDelete.bind(this, record),
    //       },
    //       auth: 'm8:machine:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setMachineChildTableData(_res: Recordable) {
    machineChildList.setColumns([
      {
        title: t('状态'),
        dataIndex: 'status',
        width: 130,
        align: 'center',
        defaultHidden: true,
        // editRow: true,
        // editComponent: 'Input',
        // editRule: true,
      },
      {
        title: t('ID'),
        dataIndex: 'id',
        width: 130,
        align: 'center',
        defaultHidden: true,
        // editRow: true,
        // editComponent: 'Input',
        // editRule: true,
      },
      {
        title: t('工序编号'),
        dataIndex: 'oper.operCode',
        width: 130,
        align: 'center',
        // editRow: true,
        // editComponent: 'Input',
        // editRule: true,
      },
      {
        title: t('工序'),
        dataIndex: 'oper.operName',
        width: 80,
        align: 'center',
        // editRow: true,
        // editComponent: 'Input',
        // editRule: false,
      },
      {
        title: t('优先等级'),
        dataIndex: 'level',
        width: 130,
        align: 'left',
        dictType: 'm8_mchine_oper_level',
        editRow: true,
        editable: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'm8_mchine_oper_level',
        },
        editRule: false,
      },
      {
        title: t('其它参数'),
        dataIndex: 'otherPro',
        width: 130,
        align: 'left',
        dictType: 'm8_machine_proType',
        // defaultValue: '1',
        editRow: true,
        editable: true,
        editComponent: 'Select',
        // editDefaultValue:1,
        editComponentProps: {
          dictType: 'm8_machine_proType',
          mode: 'multiple',
          // allowClear: true,
        },
        editRule: false,
      },
    ]);
    machineChildList.setTableData(record.value.operLevelList || []);
  }

  function handleMachineChildRowClick(record: Recordable) {
    // record.onEdit?.(true, false);
  }

  function getArrDifference(arr1, arr2) {
    return arr1.filter((item) => {
      // return arr2.some(i=>item==i)
      return arr2.some((i) => item.oper.operCode == i.oper.operCode); // 数组是对象时
    });
  }

  let listData = ref<any>();
  let listNew = ref<any>([]);

  function operChange(operCode, operName) {
    console.log(operCode, operName);

    if (!operCode) {
      operCode = '';
      operName = '';
    }
    let arr1 = operCode.split(',');
    let arr2 = operName.split(',');
    let list: any = [];
    arr1.forEach((item, index) => {
      if (item) {
        let obj = {
          oper: {
            operCode: item,
            operName: arr2[index],
          },
          level: '1',
          isNewRecord: true,
        };
        list.push(obj);
      }
    });
    // console.log(list);
    // console.log(listData.value);

    getArrDifference(listData.value, list).forEach((item, index) => {
      list.forEach((item2, index2) => {
        if (item.oper.operCode == item2.oper.operCode) {
          console.log(item, 'item11111');
          list[index2] = item;
          // item2 = item
        }
      });
    });
    listNew.value = list;
    machineChildList.setTableData(list || []);
  }

  // function handleMachineChildDelete(record: Recordable) {
  //   machineChildList.deleteTableDataRecord(record);
  // }

  async function getMachineChildList() {
    let testDataChildListValid = true;
    let testDataChildList: Recordable[] = [];
    for (const record of machineChildList.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        testDataChildListValid = false;
      }
      testDataChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of machineChildList.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      testDataChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!testDataChildListValid) {
      throw { errorFields: [{ name: ['testDataChildList'] }] };
    }
    return testDataChildList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await machineForm(data);
    record.value = (res.m8Machine || {}) as TestData;
    record.value.__t = new Date().getTime();

    listNew.value = record.value.operLevelList
    listData.value = record.value.operLevelList;
    setFieldsValue(record.value);
    updateSchema([
      {
        field: 'code',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setMachineChildTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      if (listNew.value.length != 0) {
        let arrNew = listNew.value.map((item2) => {
          return item2.oper.operCode;
        });
        listData.value.forEach((item) => {
          if (arrNew.indexOf(item.oper.operCode) <= -1) {
            listNew.value.push({
              ...item,
              // status:1
            });
            machineChildList.deleteTableDataRecord(item);
          }
        });
      } else {
        listData.value.forEach((item) => {
          if (item) {
            listNew.value.push({
              ...item,
              // status:1
            });
            machineChildList.deleteTableDataRecord(item);
          }
        });
      }

      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.operLevelList = await getMachineChildList();
      const res = await machineSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);

      // const data = await validate();
      // setDrawerProps({ confirmLoading: true });
      // const params: any = {
      //   isNewRecord: record.value.isNewRecord,
      //   id: record.value.id,
      // };
      // data.testDataChildList = await getMachineChildList();
      // // console.log('submit', params, data, record);
      // const res = await testDataSave(params, data);
      // showMessage(res.message);
      // setTimeout(closeDrawer);
      // emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
